package com.atshiyou.mvc;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Properties;


public class DispatcherServlet extends HttpServlet {
    @Override
    public void init(ServletConfig config) throws ServletException {
        String path = config.getInitParameter("contentConfiglocation");
        //servlet初始化的时候就会去加载配置文件
        InputStream is = DispatcherServlet.class.getClassLoader().getResourceAsStream(path);
        try {
            HandlerMapping.load(is);
        } catch (Exception e) {
            e.printStackTrace();
        }



    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        //获取用户请求的uri
        String requestURI = req.getRequestURI();
        HandlerMapping.MVCMapping mvcMapping = HandlerMapping.get(requestURI);
        if(requestURI == null){
            resp.sendError(404,"自定义MVC：映射地址不存在"+requestURI);
        }
        Method method = mvcMapping.getMethod();
        Object obj = mvcMapping.getObj();
        ResponseType type = mvcMapping.getType();
        Object  result = null;
        try {
            result = method.invoke(obj, req, resp);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        switch (type){
            case TEXT:
                resp.getWriter().write((String) result);
                break;
            case VIEW:
                resp.sendRedirect((String)result);
                break;
        }


    }
}
